package com.beerandjesus.sportofkings.handicapper.factory;

import com.beerandjesus.sportofkings.handicapper.dao.repository.ProfileHistoryRepository;
import com.beerandjesus.sportofkings.handicapper.model.ProfileResult;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.profile.Profile;
import com.beerandjesus.sportofkings.handicapper.profile.resolver.ProfileResolver;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Date: Jun 8, 2012
 * Time: 2:21:28 PM
 */
@Component
public class ProfileFactoryImpl implements ProfileFactory {

    private static final Logger LOG = Logger.getLogger(ProfileFactoryImpl.class);

    @Autowired
    private List<ProfileResolver> resolvers;
    @Autowired
    private ProfileHistoryRepository profileHistoryRepository;

    public List<Profile> getProfiles(HorseRace horseRace, Horse horse) {
        List<Profile> profiles = new ArrayList<Profile>();
        for (ProfileResolver resolver : getResolvers()) {
            Profile p = resolver.resolve(horseRace, horse);
            if (p != null) {
                profiles.add(p);
                ProfileResult profileResult;
                try {
                    profileResult = ProfileResultFactory.profileResult(p, horse, horseRace.getRace());
                    if (getProfileHistoryRepository().find(profileResult) == null) {
                        getProfileHistoryRepository().save(profileResult);
                    }
                } catch (ProfileResultFactory.BuildException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
        return profiles;
    }

    public List<ProfileResolver> getResolvers() {
        return resolvers;
    }

    public void setResolvers(List<ProfileResolver> resolvers) {
        this.resolvers = resolvers;
    }

    public ProfileHistoryRepository getProfileHistoryRepository() {
        return profileHistoryRepository;
    }

    public void setProfileHistoryRepository(ProfileHistoryRepository profileHistoryRepository) {
        this.profileHistoryRepository = profileHistoryRepository;
    }
}
